var dbmodel = require('./dbmodel.js');
const packInfo = require("./packInfo.js")

var col = {}
for (let i in packInfo.collection) {
	col[i] = dbmodel.model(`${i}`)
}

// add
for (let i in packInfo.crud.add) {
	exports[packInfo.crud.add[i].name] = function(data, res) {
		let info = {}
		for (let t of packInfo.crud.add[i].arg) {
			info[t] = data[t]
		}
		
		new col[i](info).save(function(err,result){
			if(err){
				res.send(packInfo.crud.add[i].err)
			}else{
				res.send(packInfo.crud.add[i].success)
			}
		})
	}
}

// read
for (let i in packInfo.crud.read) {
	exports[packInfo.crud.read[i].name] = function(data, res) {
		let info = {}
		for (let t of packInfo.crud.read[i].arg) {
			info[t] = data[t]
		}
		let out = {}
		for (let t of packInfo.crud.read[i].out) {
			out[t] = 1
		}
		col[i].find(info,out,function(err,result){
			if(err){
				res.send(packInfo.crud.read[i].err)
			}else{
				packInfo.crud.read[i].success.result = result
				res.send(packInfo.crud.read[i].success)
			}
		})
	}
}

// delete
for (let i in packInfo.crud.del) {
	exports[packInfo.crud.del[i].name] = function(data, res) {
		let arg = {}
		for (let t of packInfo.crud.del[i].arg) {
			arg[t] = data[t]
		}
		col[i].deleteOne(arg,function(err,result){
			if (err) {
				res.send(packInfo.crud.del[i].err)
			} else {
				res.send(packInfo.crud.del[i].success)
			}
		})
	}
}

// delete
for (let i in packInfo.crud.update) {
	exports[packInfo.crud.update[i].name] = function(data, res) {
		let arg = {}
		for (let t of packInfo.crud.update[i].arg) {
			arg[t] = data[t]
		}
		let updateInfo = {}
		for (let t in packInfo.collection[i]) {
			updateInfo[t] = data[t]
		}
		col[i].updateOne(arg,updateInfo,function(err,result){
			if (err) {
				res.send(packInfo.crud.update[i].err)
			} else {
				res.send(packInfo.crud.update[i].success)
			}
		})
	}
}
